package public

import (
	"github.com/gin-gonic/gin"
	"go-interview-forum/global"
	"go-interview-forum/resp"
	"go-interview-forum/service/public"
	"regexp"
)

type SendSmsInfo struct {
	Mobile string `json:"mobile"`
	From   string `json:"from"`
}

func SendSms(c *gin.Context) {
	var smsInfo SendSmsInfo
	err := c.ShouldBind(&smsInfo)
	if err != nil {
		resp.QueryErrorResp(c, "参数错误")
		return
	}

	if smsInfo.From == "" {
		resp.QueryErrorResp(c, "来源不能为空")
		return
	}

	if smsInfo.Mobile == "" {
		resp.QueryErrorResp(c, "手机号不能为空")
		return
	}

	compile, err := regexp.Compile(global.MOBILE_REGEXP)
	if err != nil {
		resp.ServerErrorResp(c, resp.SERVER_ERR, "正则编译错误")
		return
	}

	if !compile.Match([]byte(smsInfo.Mobile)) {
		resp.QueryErrorResp(c, "手机号错误")
		return
	}

	err = public.SendSms(smsInfo.Mobile, smsInfo.From)
	if err != nil {
		resp.ServerErrorResp(c, -2, err.Error())
		return
	}

	resp.SuccessResp(c, nil)
}
